<?php
 
 
namespace App\Services;
 
use Carbon\Carbon;
use Illuminate\Support\Str;
use Maatwebsite\Excel\Concerns\ToArray;
use App\Models\Grid;
use App\Models\Villager;

class ImportService implements ToArray {
 
    public $params;
    public $result;
 
    public function __construct ($params=[]) {
        $this->params = $params;
    }
 
    /**
     * 1：网格
     */
    public function array (array $array): void {
        switch ($this->params['type']) {
            case '1':
                $this->handleGrid($array);
                break;
            default:
                showError('导入类型错误');
                break;
        }
    }
 
    // 导入网格
    public function handleGrid (array $array) {
        // 去除表头
        unset($array[0]);
        try {
            $find_grid_arr=[];
            foreach($array as $v){
                $find_grid=Grid::query()
                    ->where('name',$v[2])
                    ->where('project_id',$this->params['project_id'])
                    ->value('id');
                if($find_grid){
                  $find_grid_arr[]=$find_grid;
                }
            }

            if($this->params['if_repeat']==2){
                if($find_grid_arr){
                    return $this->result= showData(['if_repeat'=>2],'有重复网格导入，是否覆盖导入');
                }
            }

            $del=Grid::query()
                        ->whereIn('id',$find_grid_arr)            
                        ->delete();
            foreach($array as $v){
                $grid_data['name']=$v[2];
                $grid_data['street_id']=$this->params['street_id'];
                $grid_data['village_id']=$this->params['village_id'];
                $grid_data['project_id']=$this->params['project_id'];
                $grid_data['segment_id']=$this->params['segment_id'];
                $grid_data['grid_group_id']=$this->params['grid_group_id'];
                $add_grid_id=Grid::query()->create($grid_data)->id;
              
                $name=explode('|',$v[1]);
                $identity_card=explode('|',$v[3]);
                $phone=explode('|',$v[4]);

                $del=Villager::query()
                            ->whereIn('grid_id',$find_grid_arr)            
                            ->delete();

                foreach($name as $k=> $v2){
                    $villager_data['grid_id']=$add_grid_id;
                    $villager_data['project_id']=$this->params['project_id'];
                    $villager_data['name']=$v2;
                    $villager_data['identity_card']=$identity_card[$k]??'';
                    $villager_data['phone']=$phone[$k]??'';
                    $villager_data['is_late']=$v[5]=="是"?1:0;
        
                    $add_villager=Villager::query()->create($villager_data);
                }
            }   
            return $this->result= showData(['if_repeat'=>1],'导入成功'); 
        } catch (\Exception $e) {
            return showError($e->getMessage());
        }
    }
 
}